//
//  Box.m
//  Box
//
//  Created by MajorTom on 9/7/10.
//  Copyright iphonegametutorials.com 2010. All rights reserved.
//

#import "Box.h"
#import "SceneManager.h"
#import "CompleteLayer.h"
#define TRANSITION_DURATION (1.2f)
@interface Box (Private)
-(void) removetitle;
@end

@implementation Box
@synthesize layer;
@synthesize size;
@synthesize lock;

-(id) initWithSize: (CGSize) aSize imgValue: (int) aImgValue{
	self = [super init];
	imgValue = aImgValue;
	size = aSize;
	OutBorderTile = [[Tile alloc] initWithX:-1 Y:-1];
	content = [NSMutableArray arrayWithCapacity: size.height];
	
	readyToRemoveTiles = [NSMutableSet setWithCapacity:50];
	
	for (int y=0; y<size.height; y++) {
	
       // NSLog(@"yyyy == %d",y);
		NSMutableArray *rowContent = [NSMutableArray arrayWithCapacity:size.width];
		for (int x=0; x < size.width; x++) {
        
			Tile *tile = [[Tile alloc] initWithX:x Y:y];
			[rowContent addObject:tile];
			[readyToRemoveTiles addObject:tile];
            tile.x0 = x;
            tile.y0 = y;
            tile.x = x;
            tile.y = y;
            NSLog(@"x = %d y= %d",tile.x , tile.y);
			[tile release];
            
           // NSLog(@"xxxx= %d",x);
		}
		[content addObject:rowContent];
		[content retain];
	}
	
	[readyToRemoveTiles retain];
    
    
    removetitle = [NSMutableArray  arrayWithCapacity:size.height * size.width];
	
	return self;
}

-(Tile *) objectAtX: (int) x Y: (int) y{
	if (x < 0 || x >= kBoxWidth || y < 0 || y >= kBoxHeight) {
		return OutBorderTile;
	}
	return [[content objectAtIndex: y] objectAtIndex: x];
}

-(BOOL) check:(int)picnum{
	
	NSArray *objects = [[readyToRemoveTiles objectEnumerator] allObjects];
	if ([objects count] == 0) {
		return NO;
	}
	
	int countTile = [objects count];
	for (int i=0; i<countTile; i++) {
		Tile *tile = [objects objectAtIndex:i];
		if (tile.value == 0) {
			[readyToRemoveTiles addObject:tile];
			continue;
		}
		
		tile.value = 0;
		if (tile.sprite) {
			[layer removeChild: tile.sprite cleanup:YES];
		}
	}

	[readyToRemoveTiles removeAllObjects];
    imgValue = picnum;
	NSString *name = [NSString stringWithFormat:@"%d.jpg",picnum];	
    //NSString * name = @"1.jpg";
	CCTexture2D * texture = [[CCTextureCache sharedTextureCache] addImage:name];
	NSMutableArray *imgFrames = [NSMutableArray array];
	[imgFrames removeAllObjects];
	
	for (int i = 0; i < kBoxWidth; i++) {
		for (int j = kBoxHeight -1; j >= 0; j--) {
//			CCSpriteFrame *imgFrame = [CCSpriteFrame frameWithTexture:texture rect:CGRectMake(i*100, j*100, 100, 100) offset:CGPointZero];
            
            CCSpriteFrame* imgFrame = [CCSpriteFrame frameWithTexture:texture rect:CGRectMake(i*100, j*100, 100, 100)];
			[imgFrames addObject:imgFrame];
		}
	}
	
	/*
	NSUInteger count = [imgFrames count];
    for (NSUInteger i = 0; i < count; ++i) {
        // Select a random element between i and end of array to swap with.
        int nElements = count - i;
        int n = (arc4random() % nElements) + i;
        [imgFrames exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
	*/
	
	for (int x=0; x<size.width; x++) {
		int extension = 0;
		for (int y=0; y<size.height; y++) {
			Tile *tile = [self objectAtX:x Y:y];
            
           
			if(tile.value == 0){
				extension++;
			}else if (extension == 0) {
				
			}
		}
        NSLog(@"extension count = %d",extension);
				
		for (int i=0; i<extension; i++) {
			Tile *destTile = [self objectAtX:x Y:kBoxHeight-extension+i];
			CCSpriteFrame * img = [imgFrames objectAtIndex:0];
			CCSprite *sprite = [CCSprite spriteWithSpriteFrame:img];
			[imgFrames removeObjectIdenticalTo:img];
			sprite.position = ccp(kStartX + x * kTileSize + kTileSize/2, kStartY + (kBoxHeight + i) * kTileSize + kTileSize/2 - kTileSize * extension);
			[layer addChild: sprite];

			destTile.value = (4* destTile.x) + destTile.y;
			destTile.originalValue = destTile.value;
			destTile.sprite = sprite;
			
			NSLog(@"postion x = %f y = %f",sprite.position.x , sprite.position.y);
            [removetitle addObject:destTile];
			
		}
        
        
	}
    
    [self removetitle];
	
	return YES;
}

-(BOOL) checkSolution {
	
	BOOL isSolved = true;
	
	for (int x=0; x<size.width; x++) {
		for (int y=0; y<size.height; y++) {
			Tile *tile = [self objectAtX:x Y:y];
			
			if (tile.originalValue != tile.value) {
				isSolved = false;
			}
		}
	}
	
	if (isSolved) {
		NSLog(@"The Sliding Image is Solved");
		return true;
	} else {
		NSLog(@"The Sliding Image is NOT Solved");
		return false;
	}	
	
	return true;
}

-(void) removetitle
{
    if (removetitle != nil && [removetitle count] > 0) {
        
        
        
        while ([removetitle count] > 0) {
            
            
            
            
            Tile * a = [removetitle objectAtIndex:0];
            
            Tile* b = [removetitle objectAtIndex:[removetitle count]-1];
            CCAction *actionA = [CCSequence actions:
                                 [CCMoveTo actionWithDuration:kMoveTileTime position:b.sprite.position],
                                 nil
                                 ];
            
            CCAction *actionB = [CCSequence actions:
                                 [CCMoveTo actionWithDuration:kMoveTileTime position:a.sprite.position],
                                 nil
                                 ];
            [a.sprite runAction:actionA];
            [b.sprite runAction:actionB];

            
            [a trade:b];
            
            [removetitle removeObjectIdenticalTo:a];
            [removetitle removeObjectIdenticalTo:b];
        }
    }

}

-(void) movesuccesswithstep:(int) step
{

//    CCSprite *sprite = [CCSprite spriteWithFile:@"1.jpg" rect:CGRectMake(5,40, 310, 420)];
//    sprite.position = ccp(160, 240);
//    [layer addChild:sprite];
    
    
    CCLayer *la = [CompleteLayer node];
    CompleteLayer* tmp = (CompleteLayer*)la;
    
    [tmp setPicNumtolayer:imgValue Step:step];
	[SceneManager go: la];
}

@end
